package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的uri
        String uri = request.getRequestURI();
        log.info("拦截的请求是" + uri);

        //定义放行的uri

        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断是否请求是否与数组中的请求匹配,匹配就放行
        boolean b = extracted(uri, uris);
        if (b) {
            filterChain.doFilter(request, response);
            return;
        }
        //判断是否是已登录状态
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee != null) {
            BaseContext.setCurrentId(employee);
            filterChain.doFilter(request, response);
            return;
        }



    Long user = (Long) request.getSession().getAttribute("user");
        if(user !=null) {
        BaseContext.setCurrentId(user);
        filterChain.doFilter(request, response);
        return;
    }
        R<Object> error = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(error));
        return;


    }

  public boolean extracted( String uri, String[] uris) throws IOException, ServletException {
        for (String s : uris) {
            if (PATH_MATCHER.match(s, uri)) {
                return true;

            }
        }
        return false;
    }
}
